// mircoApp/lunarCalendar/components/Li-Calendar/Li-Calendar.js
const {
  Solar,
  SolarMonth,
  HolidayUtil
} = require("../../lunar.js");

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    /**
     * @description 当前时间 yyyy-MM-dd
     */
    currentTime: {
      type: String,
      value: ''
    },
    /**
     * @description 全局标记点颜色，包括点和文字
     */
    maskColor: {
      type: String,
      value: "#D32D30"
    },
    /**
     * @description 是否显示农历，mask优先级高
     */
    showLunar: {
      type: Boolean,
      value: true
    },
    /**
     * @description 是否可以滚动
     */
    canDrag: {
      type: Boolean,
      value: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    nextDisabled: false,
    lastDisabled: false,
    currentSelectTime: undefined, //点击时保存的dateIndex
    title_time: "", //顶头文本
    year: undefined, //当前年
    month: undefined, //当前月
    beforeDateList: [], //上个月的日期列表
    dateList: [], //本月的日期列表
    afterDateList: [], //下个月的日期列表
    transform_x: 0,
    transform_time: 0
  },
  pageLifetimes: {
    show(){
      let timeObj = new Date();
      this.data.currentTime = timeObj.getFullYear() + "-" + (timeObj.getMonth() + 1) + "-" + timeObj.getDate();
      this.render();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    render(setTimeStr) {
      //初始化
      let that = this;
      let obj = {};
      let currentTimeStr = setTimeStr ? setTimeStr : that.data.currentTime;
      // console.log(currentTimeStr)
      let timeObj = this.toDateByStr(currentTimeStr); //当前选定的时间
      let m = SolarMonth.fromDate(timeObj);
      let t = Solar.fromDate(new Date());
      // 创建前面的日期
      obj.beforeDateList = [];
      obj.dateList = [];
      obj.afterDateList = [];
      obj.year = m.getYear();
      obj.month = m.getMonth();
      //计算头部显示的年月
      obj.title_time = m.getYear() + "年" + m.getMonth() + "月";
      // console.log(m.toFullString())
      let weeks = m.getWeeks(0);
      // console.log(weeks)
      for (let i = 0, j = weeks.length; i < j; i++) {
        let days = weeks[i].getDays();
        for (let k = 0, l = days.length; k < l; k++) {
          let tempObj = {
            isToday: false
          };
          // console.log(days[k])
          let lu = days[k].getLunar();
          // 周末
          if (k == 0 || k == 6) {
            tempObj.isDaySunOrSat = true;
          }
          // 节假日
          let ho = HolidayUtil.getHoliday(days[k].toYmd());
          if (ho) {
            if (ho.isWork()) {
              // 调休
              tempObj.pointText = "班";
              tempObj.pointTextColor = "#0081ff";
            } else {
              // 放假
              tempObj.pointText = "休";
              tempObj.pointTextColor = "#D32D30";
            }
            if (ho.getTarget() == days[k].toYmd()) {
              tempObj.markText = ho.getName();
              tempObj.markTextColor = "#D32D30";
            }
          }
          // 节气
          if (!tempObj.markText) {
            let jie = lu.getJieQi();
            if (jie) {
              tempObj.markText = jie;
              tempObj.markTextColor = "#D32D30";
              // console.log(jie);
            }
          }
          // 农历
          if (!tempObj.markText) {
            // 农历
            let tempLunarDay = lu.getDayInChinese() == "初一" ? lu.getMonthInChinese() + "月" : lu.getDayInChinese();
            tempObj.markText = tempLunarDay;
            tempObj.markTextColor = "#A8A8A8";
          }
          // 当日
          if (days[k].getYear() == t.getYear() && days[k].getMonth() == t.getMonth() && days[k].getDay() == t.getDay()) {
            tempObj.isToday = true;
          }
          if (m.getYear() > days[k].getYear() || (m.getYear() == days[k].getYear() && m.getMonth() > days[k].getMonth())) {
            tempObj.key = "before_" + days[k].getDay();
            tempObj.dateIndex = days[k].getDay();
            obj.beforeDateList.push(tempObj);
            // console.log('当月前' + tempObj.key)
          } else if (m.getYear() < days[k].getYear() || (m.getYear() == days[k].getYear() && m.getMonth() < days[k].getMonth())) {
            tempObj.key = "after_" + days[k].getDay();
            tempObj.dateIndex = days[k].getDay();
            obj.afterDateList.push(tempObj);
            // console.log('当月后' + tempObj.key)
          } else {
            tempObj.key = "date_" + days[k].getDay();
            tempObj.dateIndex = days[k].getDay();
            obj.dateList.push(tempObj);
            // console.log('当月' + tempObj.key)
          }
        }
      }
      console.log(obj)
      this.setData(obj);
    },
    dateChange(e) {
      let selectDate = undefined;
      if (e.type == "change") {
        selectDate = new Date(e.detail.value);
      }
      if (!selectDate) {
        return;
      }
      //如果已经是当月
      if (selectDate.getFullYear() == this.year && selectDate.getMonth() + 1 == this.month && selectDate.getDate() == t.currentSelectTime) {
        console.log("无变化 不需要加载");
        return;
      }
      let value = selectDate.getFullYear() + "/" + (selectDate.getMonth() + 1) + "/" + selectDate.getDate();
      this.triggerEvent("monthChange", {
        date: value
      });
      this.render(value);
      this.selectedDateFun(selectDate.getDate());
    },
    toDateByStr(timeStr) {
      //字符串转换时间，转换失败或者不传字符串则返回当前
      let timeObj;
      if (timeStr) {
        timeObj = new Date(timeStr.replace(/-/g, "/"));
      }
      if (!timeStr || timeObj == "Invalid Date") timeObj = new Date();
      return timeObj;
    },
    selectedDateFun(e) {
      let index = e?.currentTarget?.dataset?.index || e;
      //点击日期
      let that = this;
      let selectObj = that.data.dateList[index - 1];
      selectObj.year = that.data.year;
      selectObj.month = that.data.month;
      selectObj.day = index;
      selectObj.time = that.data.year + "/" + that.data.month + "/" + index;
      that.triggerEvent("dayChange", selectObj);
      this.setData({
        currentSelectTime: index
      });
    },
    addMonth() {
      //加一个月
      let month = SolarMonth.fromYm(this.data.year, this.data.month);
      month = month.next(1);
      let value = month.getYear() + "/" + month.getMonth() + "/1";

      this.triggerEvent("monthChange", {
        date: value
      });
      this.render(value);
      this.selectedDateFun(1);
    },
    subMonth() {
      //减一个月
      let month = SolarMonth.fromYm(this.data.year, this.data.month);
      month = month.next(-1);
      let value = month.getYear() + "/" + month.getMonth() + "/1";

      this.triggerEvent("monthChange", {
        date: value
      });
      this.render(value);
      this.selectedDateFun(1);
    },
    backToToday() {
      //回到今天
      let currDate = new Date();
      let _year = currDate.getFullYear();
      let _month = currDate.getMonth() + 1;
      let _day = currDate.getDate();

      //如果已经是当月
      if (_year == this.data.year && _month == this.data.month && _day == this.data.currentSelectTime) {
        console.log("无变化 不需要加载");
        return;
      }

      let value = _year + "/" + _month + "/" + _day;

      this.triggerEvent("monthChange", {
        date: value
      });
      this.render(value);
      this.selectedDateFun(_day);
    },

    calendarTransform(x, time) {
      //日历滑动动画
      this.setData({
        transform_x: x,
        transform_time: time
      });
    },
    touchstart(event) {
      if (!this.data.canDrag) return;
      this.setData({
        startPageX: event.touches[0].pageX,
        startPageY: event.touches[0].pageY
      });
    },
    touchmove(event) {
      if (!this.data.canDrag) return;
      let touchmovePageX = event.touches[0].pageX;
      let result = touchmovePageX - this.data.startPageX;
      this.calendarTransform(result, 0);
    },
    touchend(event) {
      if (!this.data.canDrag) return;
      let that = this;
      let endPageX = event.changedTouches[0].pageX;
      let endPageY = event.changedTouches[0].pageY;
      let x = Math.abs(that.startPageX - endPageX); //横坐标之差
      let y = Math.abs(that.startPageY - endPageY); //纵坐标之差

      let screenX = 345;
      // try {
      //   const res = uni.getSystemInfoSync();
      //   screenX = res.windowWidth;
      // } catch (e) {
      //   console.error(e);
      //   return;
      // }
      if (that.data.startPageX > endPageX) {
        //左滑
        let a = Math.atan(y / x);
        let Rate = x / screenX;
        if (a < Math.PI / 6 && Rate > 0.3) {
          screenX = -screenX;
          that.calendarTransform(screenX, 300);
          setTimeout(function () {
            that.addMonth();
            that.calendarTransform(0, 0);
          }, 300);
        } else {
          that.calendarTransform(0, 300);
        }
      } else {
        let a = Math.atan(y / x);
        let Rate = x / screenX;
        if (a < Math.PI / 6 && Rate > 0.3) {
          that.calendarTransform(screenX, 300);
          setTimeout(function () {
            that.subMonth();
            that.calendarTransform(0, 0);
          }, 300);
        } else {
          that.calendarTransform(0, 300);
        }
      }
    }
  },
})